package com.iven.xie.redis.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.iven.xie.redis.beans.RedisConfig;
import com.iven.xie.redis.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;

/**
 * @author xiezhendong
 * @date 2021/7/26
 */
@Service
public class ConfigServiceImpl implements ConfigService {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeOut;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    private int maxWaitMillis;

    @Autowired
    JedisPool pool;

    @Override
    public RedisConfig getDefaultConfig() {
        RedisConfig redisConfig = new RedisConfig();
        redisConfig.setHost(host);
        redisConfig.setPort(port);
        redisConfig.setTimeOut(timeOut);
        redisConfig.setMaxIdle(maxIdle);
        redisConfig.setMaxWaitMillis(maxWaitMillis);
        return redisConfig;
    }

    private static final String REDIS_SETTING_KEY = "redisSettingKey";

    @Override
    public List<RedisConfig> getSettingList() {
        Jedis jedis = null;
        String listData = null;
        try {
            jedis = pool.getResource();
            jedis.select(0);
            listData = jedis.get(REDIS_SETTING_KEY);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        List<RedisConfig> list = JSON.parseArray(listData, RedisConfig.class);
        if (CollectionUtils.isEmpty(list)) {
            list = Lists.newArrayList();
        }
        list.add(this.getDefaultConfig());

        return list;
    }

    @Override
    public List<RedisConfig> addSetting(RedisConfig config) throws IOException {
        Jedis jedis = null;
        List<RedisConfig> list = Lists.newArrayList();
        try {
            jedis = pool.getResource();
            jedis.select(0);
            String listData = jedis.get(REDIS_SETTING_KEY);
            if (listData != null && !"".equals(listData)) {
                list = JSON.parseArray(listData, RedisConfig.class);
            }
            list.add(config);
            jedis.select(0);
            jedis.set(REDIS_SETTING_KEY, JSON.toJSONString(list));
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        if (CollectionUtils.isEmpty(list)) {
            list = Lists.newArrayList();
        }
        list.add(this.getDefaultConfig());

        return list;
    }
}
